<template>
    <view class="home-page">
        <view class="home-page-contain">
            <view class="home-page-title"></view>
            <view class="home-page-in"></view>
            <view class="home-page-btns" v-if="!userInfo['phone']">
                <button class="btn-unit" hover-class="btn_submit" @click.native.prevent="notOnSubmit('检测')" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">检测单位</button>
                <button class="btn-unit btn-mar" hover-class="btn_submit" @click.native.prevent="notOnSubmit('管理')" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">管理单位</button>
            </view>
            <view class="home-page-btns" v-else>
                <button class="btn-unit" hover-class="btn_submit" @click.native.prevent="onSubmit('检测')">检测单位</button>
                <button class="btn-unit btn-mar" hover-class="btn_submit" @click.native.prevent="onSubmit('管理')">管理单位</button>
            </view>
        </view>
    </view>
</template>

<script>
import { wxGetToken, wxGetUserPhoneNumber, getByUserPhone, userLogin, getByUserId } from '@/service/user';

export default {
    name: 'AuthHomePage',
    data() {
        return {
            unit: '',
            userInfo: ''
        }
    },
    created() {
        this.userInfo = this.$Cookies.get('userInfo') || {}
    },
    methods: {
        async onGetPhoneNumber(event) {
            // 先清除所有数据
            this.$Cookies.clear()
            // 获取事件内容
            const { code } = event.detail;
            // 获取信息
            const tokenRes = await wxGetToken();
            // 解析手机号
            const userRes = await wxGetUserPhoneNumber(tokenRes['access_token'], {code});
            // 用户登录 - 临时使用
            // let data = {
            //     userName: 'liuliu',
            //     password: 'Abc123456.'
            // };
            // const loginRes = await userLogin(data);
            // 存储token - 临时使用
            // this.$Cookies.set('token', loginRes['token'])
            // 获取用户信息
            const phoneNumber = userRes['phone_info']['phoneNumber'];
            const userInfo = await getByUserPhone(phoneNumber);
            this.$Cookies.set('userInfo', userInfo['data'])
            this.$Cookies.set('token', userInfo['data']['token'])
            // 获取用户权限
            const { userId } = userInfo['data']
            const authRes = await getByUserId(userId);
            // 用户是否属于管理者
            let isManage,isUser;
            authRes['data'].find(ele => {
                if( (ele['roleKey'] == 'User') || (ele['roleKey'] == 'manageAgency')) {
                    isUser = true;
                }
                if( (ele['roleKey'] == 'Administrator') || (ele['roleKey'] == 'manageAgency')) {
                    isManage = true;
                }
            })
            if( this.unit === '检测' ) {
                if( isUser === true || isManage === true ) {
                    let url = `/pages/cloudRecordSystem/index`;
                    this.$Router.redirect(url);
                }
            } else if( this.unit === '管理' ) {
                if( isManage === true ) {
                    uni.scanCode({
                        onlyFromCamera: true,
                        scanType: ['qrCode', 'datamatrix', 'pdf417'],
                        success: (res) => {
                            // 'https://qcsci.com?reportId=3b8b44e0fe454d94a719834d1cd58cbb'
                            if( res.result.includes('reportId') ) {
                                let str = res.result.replace('https://qcsci.com?','');
                                let url = `/pages/reportList/index?${str}`;
                                this.$Router.push(url);
                            }
                        }
                    });
                }
            }
        },
        notOnSubmit(unit) {
            this.unit = unit
        },
        async onSubmit(unit) {
            // 获取手机号
            let phoneNumber = this.userInfo['phone'];
            // 先清除所有数据
            this.$Cookies.clear()
            // 调用手机号登录接口
            const userInfo = await getByUserPhone(phoneNumber);
            this.$Cookies.set('userInfo', userInfo['data'])
            this.$Cookies.set('token', userInfo['data']['token'])
            // 获取用户权限
            const { userId } = userInfo['data']
            const authRes = await getByUserId(userId);
            // 用户是否属于管理者
            let isManage,isUser;
            authRes['data'].find(ele => {
                if( (ele['roleKey'] == 'User') || (ele['roleKey'] == 'manageAgency')) {
                    isUser = true;
                }
                if( (ele['roleKey'] == 'Administrator') || (ele['roleKey'] == 'manageAgency')) {
                    isManage = true;
                }
            })
            if( unit === '检测' ) {
                if( isUser === true || isManage === true ) {
                    let url = `/pages/cloudRecordSystem/index`;
                    this.$Router.redirect(url);
                }
            } else if( unit === '管理' ) {
                if( isManage === true ) {
                    uni.scanCode({
                        onlyFromCamera: true,
                        scanType: ['qrCode', 'datamatrix', 'pdf417'],
                        success: (res) => {
                            // 'https://qcsci.com?reportId=3b8b44e0fe454d94a719834d1cd58cbb'
                            if( res.result.includes('reportId') ) {
                                let str = res.result.replace('https://qcsci.com?','');
                                let url = `/pages/reportList/index?${str}`;
                                this.$Router.push(url);
                            }
                        }
                    });
                }
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.home-page {
    width: 100%;
    height: 100%;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    background-image: url($uni-image-ip+'/logo-bg.png');
    position: relative;
    .home-page-contain {
        position: absolute;
        top: 36%;
        left: 50%;
        transform: translate(-50%, -50%);
        .home-page-title {
            width: 510rpx;
            height: 154rpx;
            background-repeat: no-repeat;
            background-size: 100% 100%;
            background-image: url($uni-image-ip+'/logo-title.png');
        }
        .home-page-in {
            height: 144rpx;
        }
        .home-page-btns {
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
        }
        .btn-unit {
            width: 330rpx;
            height: 98rpx;
            background-repeat: no-repeat;
            background-size: 100% 100%;
            background-image: url($uni-image-ip+'/logo-btn.png');

            text-align: center;
            line-height: 98rpx;
            color: #FFFFFF;
            background-color: transparent;
            font-family: YouSheBiaoTiHei;
            font-size: 30rpx;
            font-weight: bold;
            color: #FFFFFF;
            letter-spacing: 2rpx;
        }
        .btn-mar {
            margin-top: 82rpx;
        }
    }
}
</style>